package com.hksj.data.event.listener;

import com.alibaba.fastjson.JSONObject;
import com.hksj.data.event.WriteRawMysqlDataEvent;
import com.hksj.data.mysql.entity.DeviceMetadataInfo;
import com.hksj.data.mysql.service.DeviceMetadataInfoService;
import com.hksj.data.service.DevicePropertyService;
import com.hksj.data.thing.RawData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.Map;

/**
 * @author zengke
 * @version 1.0
 * @see WriteRawMysqlDataEventListener
 * @since 2025/08/15 10:21
 */

@Component
public class WriteRawMysqlDataEventListener {

    @Autowired
    private DeviceMetadataInfoService deviceMetadataInfoService;

    @Async
    @EventListener
    public void onWriteRawMysqlDataEvent(WriteRawMysqlDataEvent event) {

        //获取原始数据
        //获取原始数据
        RawData data = event.getData();

        //获取上报时间戳
        Long timestamp = data.getTimestamp();

        //获取设备id
        String deviceId = data.getDeviceId();

        //判断设备id是否为空
        if (deviceId == null){
            return;
        }

        //获取数据集合
        Map<String, Object> dataMap = data.getDataMap();

        //判断数据集合是否为空
        if (dataMap == null){
            return;
        }

        //原始的json数据
        String content = JSONObject.toJSONString(dataMap);

        //创建设备原始数据对象
        //设备原始数据对象
        DeviceMetadataInfo entity = new DeviceMetadataInfo();

        //设置对象的各属性值
        entity.setDeviceId(deviceId);
        entity.setContent(content);
        entity.setType("reportProperty");

        //查询是否存在该设备的原始数据信息
        DeviceMetadataInfo deviceMetadataInfo = deviceMetadataInfoService.lambdaQuery().eq(DeviceMetadataInfo::getDeviceId, deviceId).one();

        //判断是否存在
        if (ObjectUtils.isEmpty(deviceMetadataInfo)){

            //不存在、做新增
            entity.setCreateTime(new Date(timestamp));
            entity.setUpdateTime(new Date(timestamp));
        } else {

            //存在做更新
            entity.setId(deviceMetadataInfo.getId());
            entity.setUpdateTime(new Date(timestamp));
        }

        //新增或更新设备原始数据
        deviceMetadataInfoService.saveOrUpdate(entity);
    }
}
